package com.itheima.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.constant.Constants;
import com.itheima.bos.dao.base.AreaRepository;
import com.itheima.bos.dao.base.FixedAreaRepository;
import com.itheima.bos.dao.take_delivery.OrderRepository;
import com.itheima.bos.dao.take_delivery.WorkBillRepository;
import com.itheima.bos.domain.base.Area;
import com.itheima.bos.domain.base.Courier;
import com.itheima.bos.domain.base.FixedArea;
import com.itheima.bos.domain.base.SubArea;
import com.itheima.bos.domain.take_delivery.Order;
import com.itheima.bos.domain.take_delivery.WorkBill;
import com.itheima.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private FixedAreaRepository fixedAreaRepository;

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private AreaRepository areaRepository;

	@Autowired
	private WorkBillRepository workBillRepository;

	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsQueueTemplate;

	@Override
	public void saveOrder(Order order) {

		order.setOrderNum(UUID.randomUUID().toString());// 设置订单号
		order.setOrderTime(new Date());// 订单时间
		order.setStatus("1");// 订单状态,为代取件

		/*
		 * 之前封装的sendArea和recArea中,无id
		 */
		Area area = order.getSendArea();
		Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(area.getProvince(), area.getCity(),
				area.getDistrict());

		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());

		order.setSendArea(persistArea);
		order.setRecArea(persistRecArea);

		// 自动分单逻辑,基于CRM地址库完全匹配,获取定区,匹配快递员
		String fixAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL
				+ "/services/customerService/customer/findFixedAreaIdByAddress?sendAddress=" + order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		
		if (StringUtils.isNoneBlank(fixAreaId)) {
			// 路径完全匹配,自动分单成功
			// 根据fixedAreaRepository查询出快递员
			FixedArea fixedArea = fixedAreaRepository.findOne(fixAreaId);
			
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()){
				Courier courier = iterator.next();
				if (courier != null) {
					System.out.println("自动分单成功...");
					
					saveOrder(order, courier);
					
					// 生成工单,发送短信
					generateWorkBill(order);
					return;
				}
			}
		}

		// 自动分单,路径没有完全匹配,通过order的省市区,查询分区的关键字,匹配地址,基于分区实现自动单
		for (SubArea subArea : persistArea.getSubareas()) {
			// 当前客户下单的地址是否保护分区的关键字
			if (order.getSendAddress().contains(subArea.getKeyWords()) ||
					order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				// 找到对应的分区,从而找到对应的快递员
				FixedArea fixedArea = subArea.getFixedArea();
				
				Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
				if (iterator.hasNext()){
					Courier courier = iterator.next();
					if (courier != null) {
						System.out.println("自动分单成功...");
						
						saveOrder(order, courier);
						
						// 生成工单,发送短信
						generateWorkBill(order);
						return;
					}
				}

			}
		}

		// 人工分单
		order.setOrderType("2");
		orderRepository.save(order);

	}

	// 生成工单,发送短信
	private void generateWorkBill(final Order order) {

		WorkBill workBill = new WorkBill();
		workBill.setType("新"); // 工单类型
		workBill.setPickstate("取件状态"); // 取件状态
		workBill.setBuildtime(new Date()); // 工单生成时间
		workBill.setAttachbilltimes(0); // 追单次数
		workBill.setRemark(order.getRemark());// 备注
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber); // 短信序号
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);

		//// 发送短信
		// 调用MQ服务，发送一条消息
		/*jmsQueueTemplate.send("workbill",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier()
						.getTelephone());
				mapMessage.setString("msg","短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
				+ ",联系人:" + order.getSendName() + ",手机:"
				+ order.getSendMobile() + "，快递员捎话："
				+ order.getSendMobileMsg());
				
				return mapMessage;
			}
		});*/

		workBill.setPickstate("已通知"); // 取件状态
		// 保存工单
		workBillRepository.save(workBill);
	}

	// 自动分单保存抽取的方法
	private void saveOrder(Order order, Courier courier) {
		// 并将快递员关联至订单
		order.setCourier(courier);
		// 设置自动分单
		order.setOrderType("1");
		orderRepository.save(order);
	}

	/*
	 * 根据订单的订单号查询订单
	 */
	@Override
	public Order findByOrderNum(String orderNum) {
		
		return orderRepository.findByOrderNum(orderNum);
	}

}
